// 扑克牌工具类

const SUITS = ['spades', 'hearts', 'clubs', 'diamonds']; // 黑桃、红心、梅花、方块
const RANKS = ['3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A', '2'];
const RANK_VALUES = {
  '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, '10': 10,
  'J': 11, 'Q': 12, 'K': 13, 'A': 14, '2': 15
};

class CardDeck {
  // 创建一副牌（54张：52张普通牌 + 2张王）
  static createDeck() {
    const deck = [];
    let id = 1;

    // 52张普通牌
    for (const suit of SUITS) {
      for (const rank of RANKS) {
        deck.push({
          id: id++,
          suit,
          rank,
          value: RANK_VALUES[rank],
          display: this.getCardDisplay(suit, rank)
        });
      }
    }

    // 小王
    deck.push({
      id: id++,
      suit: 'joker',
      rank: 'small',
      value: 16,
      display: '🃏'
    });

    // 大王
    deck.push({
      id: id++,
      suit: 'joker',
      rank: 'big',
      value: 17,
      display: '🃟'
    });

    return deck;
  }

  // 获取卡牌显示
  static getCardDisplay(suit, rank) {
    const suitSymbols = {
      'spades': '♠',
      'hearts': '♥',
      'clubs': '♣',
      'diamonds': '♦'
    };
    return `${suitSymbols[suit]}${rank}`;
  }

  // 洗牌（Fisher-Yates 算法）
  static shuffle(deck) {
    const shuffled = [...deck];
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
    }
    return shuffled;
  }

  // 发牌
  static deal(deck, playerCount) {
    if (playerCount !== 3) {
      throw new Error('目前只支持3人游戏');
    }

    const hands = [[], [], []];
    
    // 每人发18张牌
    for (let i = 0; i < 54; i++) {
      hands[i % 3].push(deck[i]);
    }

    // 对每个玩家的手牌排序
    hands.forEach(hand => {
      hand.sort((a, b) => {
        if (a.value !== b.value) {
          return a.value - b.value;
        }
        return SUITS.indexOf(a.suit) - SUITS.indexOf(b.suit);
      });
    });

    return hands;
  }

  // 按花色分组
  static groupBySuit(cards) {
    const groups = {
      spades: [],
      hearts: [],
      clubs: [],
      diamonds: [],
      joker: []
    };

    cards.forEach(card => {
      groups[card.suit].push(card);
    });

    return groups;
  }

  // 按点数分组
  static groupByRank(cards) {
    const groups = {};
    
    cards.forEach(card => {
      if (!groups[card.rank]) {
        groups[card.rank] = [];
      }
      groups[card.rank].push(card);
    });

    return groups;
  }
}

module.exports = CardDeck;
